<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入优惠券名称" clearable />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择优惠券类型" clearable>
            <el-option label="满减券" value="1" />
            <el-option label="折扣券" value="2" />
            <el-option label="无门槛券" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="使用状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择使用状态" clearable>
            <el-option label="未开始" value="0" />
            <el-option label="进行中" value="1" />
            <el-option label="已结束" value="2" />
            <el-option label="已停用" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="发放时间" prop="time">
          <el-date-picker
            v-model="queryParams.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd">新增优惠券</el-button>
      <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
        批量删除
      </el-button>
      <el-button type="success" @click="handleExport">导出数据</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="couponList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="优惠券名称" prop="name" min-width="150" />
      <el-table-column label="优惠券类型" prop="type" width="100">
        <template #default="{ row }">
          <el-tag :type="getTypeTag(row.type)">
            {{ getTypeName(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优惠内容" min-width="150">
        <template #default="{ row }">
          <template v-if="row.type === '1'">
            满{{ row.minAmount }}减{{ row.amount }}
          </template>
          <template v-else-if="row.type === '2'">
            {{ row.discount }}折
          </template>
          <template v-else>
            {{ row.amount }}元
          </template>
        </template>
      </el-table-column>
      <el-table-column label="使用门槛" prop="minAmount" width="100">
        <template #default="{ row }">
          {{ row.type === '3' ? '无门槛' : `满${row.minAmount}元` }}
        </template>
      </el-table-column>
      <el-table-column label="有效期" min-width="300">
        <template #default="{ row }">
          {{ row.startTime }} 至 {{ row.endTime }}
        </template>
      </el-table-column>
      <el-table-column label="发放数量" prop="total" width="100" />
      <el-table-column label="已领取" prop="received" width="100" />
      <el-table-column label="已使用" prop="used" width="100" />
      <el-table-column label="状态" prop="status" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTag(row.status)">
            {{ getStatusName(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="primary" link @click="handleDetail(row)">详情</el-button>
          <el-button 
            v-if="row.status === '0'"
            type="success" 
            link 
            @click="handleStart(row)"
          >
            开始
          </el-button>
          <el-button 
            v-if="row.status === '1'"
            type="warning" 
            link 
            @click="handleStop(row)"
          >
            停用
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="600px"
      append-to-body
    >
      <el-form
        ref="couponForm"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择优惠券类型" @change="handleTypeChange">
            <el-option label="满减券" value="1" />
            <el-option label="折扣券" value="2" />
            <el-option label="无门槛券" value="3" />
          </el-select>
        </el-form-item>
        <template v-if="form.type === '1'">
          <el-form-item label="优惠金额" prop="amount">
            <el-input-number v-model="form.amount" :min="0" :precision="2" :step="1" />
            <span class="unit">元</span>
          </el-form-item>
          <el-form-item label="使用门槛" prop="minAmount">
            <el-input-number v-model="form.minAmount" :min="0" :precision="2" :step="1" />
            <span class="unit">元</span>
          </el-form-item>
        </template>
        <template v-else-if="form.type === '2'">
          <el-form-item label="折扣率" prop="discount">
            <el-input-number
              v-model="form.discount"
              :min="0"
              :max="10"
              :precision="1"
              :step="0.1"
            />
            <span class="unit">折</span>
          </el-form-item>
          <el-form-item label="使用门槛" prop="minAmount">
            <el-input-number v-model="form.minAmount" :min="0" :precision="2" :step="1" />
            <span class="unit">元</span>
          </el-form-item>
        </template>
        <template v-else-if="form.type === '3'">
          <el-form-item label="优惠金额" prop="amount">
            <el-input-number v-model="form.amount" :min="0" :precision="2" :step="1" />
            <span class="unit">元</span>
          </el-form-item>
        </template>
        <el-form-item label="有效期" prop="time">
          <el-date-picker
            v-model="form.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="发放数量" prop="total">
          <el-input-number v-model="form.total" :min="0" :step="100" />
          <span class="unit">张</span>
        </el-form-item>
        <el-form-item label="每人限领" prop="perLimit">
          <el-input-number v-model="form.perLimit" :min="1" :step="1" />
          <span class="unit">张</span>
        </el-form-item>
        <el-form-item label="使用说明" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入使用说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCouponList, addCoupon, updateCoupon, deleteCoupon, batchDeleteCoupon, startCoupon, stopCoupon } from '@/api/marketing'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  type: '',
  status: '',
  time: []
})

// 表单参数
const form = reactive({
  id: undefined,
  name: '',
  type: '',
  amount: 0,
  discount: 10,
  minAmount: 0,
  time: [],
  total: 1000,
  perLimit: 1,
  description: ''
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '优惠券名称不能为空', trigger: 'blur' },
    { min: 2, max: 50, message: '优惠券名称长度必须在2到50个字符之间', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择优惠券类型', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入优惠金额', trigger: 'blur' }
  ],
  discount: [
    { required: true, message: '请输入折扣率', trigger: 'blur' }
  ],
  minAmount: [
    { required: true, message: '请输入使用门槛', trigger: 'blur' }
  ],
  time: [
    { required: true, message: '请选择有效期', trigger: 'change' }
  ],
  total: [
    { required: true, message: '请输入发放数量', trigger: 'blur' }
  ],
  perLimit: [
    { required: true, message: '请输入每人限领数量', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入使用说明', trigger: 'blur' }
  ]
}

// 数据列表
const couponList = ref([])
const loading = ref(false)
const total = ref(0)
const selectedIds = ref([])

// 对话框
const dialog = reactive({
  visible: false,
  title: ''
})

// 表单引用
const couponForm = ref()

// 获取优惠券类型标签样式
const getTypeTag = (type) => {
  const map = {
    '1': 'success',
    '2': 'warning',
    '3': 'info'
  }
  return map[type] || ''
}

// 获取优惠券类型名称
const getTypeName = (type) => {
  const map = {
    '1': '满减券',
    '2': '折扣券',
    '3': '无门槛券'
  }
  return map[type] || ''
}

// 获取优惠券状态标签样式
const getStatusTag = (status) => {
  const map = {
    '0': 'info',
    '1': 'success',
    '2': 'danger',
    '3': 'warning'
  }
  return map[status] || ''
}

// 获取优惠券状态名称
const getStatusName = (status) => {
  const map = {
    '0': '未开始',
    '1': '进行中',
    '2': '已结束',
    '3': '已停用'
  }
  return map[status] || ''
}

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const { data } = await getCouponList(queryParams)
    couponList.value = data.list || []
    total.value = data.total || 0
  } catch (error) {
    console.error('获取优惠券列表失败:', error)
    ElMessage.error('获取优惠券列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮
const resetQuery = () => {
  queryParams.name = ''
  queryParams.type = ''
  queryParams.status = ''
  queryParams.time = []
  handleQuery()
}

// 选择项变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增按钮
const handleAdd = () => {
  dialog.title = '添加优惠券'
  dialog.visible = true
  Object.assign(form, {
    id: undefined,
    name: '',
    type: '',
    amount: 0,
    discount: 10,
    minAmount: 0,
    time: [],
    total: 1000,
    perLimit: 1,
    description: ''
  })
}

// 编辑按钮
const handleEdit = (row) => {
  dialog.title = '编辑优惠券'
  dialog.visible = true
  Object.assign(form, {
    ...row,
    time: [row.startTime, row.endTime]
  })
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该优惠券吗？', '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteCoupon(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除优惠券失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要删除的优惠券')
    return
  }
  ElMessageBox.confirm(`确认要删除选中的 ${selectedIds.value.length} 个优惠券吗？`, '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      await batchDeleteCoupon(selectedIds.value)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('批量删除优惠券失败:', error)
      ElMessage.error('批量删除失败')
    }
  })
}

// 开始发放
const handleStart = (row) => {
  ElMessageBox.confirm('确认要开始发放该优惠券吗？', '提示', {
    type: 'info'
  }).then(async () => {
    try {
      await startCoupon(row.id)
      ElMessage.success('优惠券已开始发放')
      getList()
    } catch (error) {
      console.error('开始发放优惠券失败:', error)
      ElMessage.error('开始发放失败')
    }
  })
}

// 停止发放
const handleStop = (row) => {
  ElMessageBox.confirm('确认要停止发放该优惠券吗？', '提示', {
    type: 'info'
  }).then(async () => {
    try {
      await stopCoupon(row.id)
      ElMessage.success('优惠券已停止发放')
      getList()
    } catch (error) {
      console.error('停止发放优惠券失败:', error)
      ElMessage.error('停止发放失败')
    }
  })
}

// 导出数据
const handleExport = async () => {
  try {
    // TODO: 实现导出功能
    ElMessage.info('导出功能开发中')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 优惠券类型变化
const handleTypeChange = (type) => {
  if (type === '3') {
    form.minAmount = 0
  }
}

// 提交表单
const submitForm = async () => {
  await couponForm.value.validate()
  try {
    const [startTime, endTime] = form.time
    const submitData = {
      ...form,
      startTime,
      endTime
    }
    delete submitData.time

    if (form.id) {
      await updateCoupon(submitData)
    } else {
      await addCoupon(submitData)
    }
    ElMessage.success('保存成功')
    dialog.visible = false
    getList()
  } catch (error) {
    console.error('保存优惠券失败:', error)
    ElMessage.error('保存失败')
  }
}

// 取消按钮
const cancel = () => {
  dialog.visible = false
  couponForm.value?.resetFields()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 详情按钮
const handleDetail = (row) => {
  // TODO: 实现查看详情功能
  ElMessage.info('详情功能开发中')
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .search-bar {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
  }
  
  .action-bar {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .unit {
    margin-left: 8px;
    color: var(--el-text-color-secondary);
  }
}
</style> 